package com.genesis.yunnanji.fragment;

import android.content.Context;
import android.content.Intent;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.xutils.x;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.genesis.yunnanji.R;
import com.genesis.yunnanji.activity.SupDetails;
import com.genesis.yunnanji.activity.WebActivity;
import com.genesis.yunnanji.adapter.ExplorationRoomAdapter;
import com.genesis.yunnanji.adapter.OneAdapter;
import com.genesis.yunnanji.adapter.TwoAdapter;
import com.genesis.yunnanji.bean.ExplorationRoomBean;
import com.genesis.yunnanji.bean.HomePageListBean;
import com.genesis.yunnanji.bean.SpecialtyBannerBean;
import com.genesis.yunnanji.config.GenesisApiConfig;
import com.genesis.yunnanji.utils.NetWorkUtils;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.luck.picture.lib.decoration.GridSpacingItemDecoration;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * 创建日期：2018/10/26 00269:44
 * 作者：Kite
 * 描述：体验馆
 */
public class ExplorationRoomFragment extends Fragment {

    private View view;

    private int page = 0;

    public View nodata;

    private Banner banner;

    private RecyclerView rvRoom;

    private RecyclerView rvHot;

    private ExplorationRoomAdapter mExplorationRoomAdapter;

    private List<SpecialtyBannerBean.ResultBean.ListBean> bannerList = new ArrayList<>();//后台返回banner图

    public static ExplorationRoomFragment newInstance(String param) {
        ExplorationRoomFragment obj = new ExplorationRoomFragment();
        Bundle bundle = new Bundle();
        bundle.putString("args1", param);
        obj.setArguments(bundle);
        return obj;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = this.getActivity().getLayoutInflater().inflate(R.layout.fragment_exploration_room, null);
            initView();
        } else {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeView(view);
            }
        }
        return view;
    }

    private void initView() {
        getNewsData();
        rvHot = view.findViewById(R.id.rvHot);
        rvRoom = view.findViewById(R.id.rvRoom);
        banner = view.findViewById(R.id.room_banner);
        netBanner();
//        setUpView();
    }

//    protected void setUpView() {
//        LoadingView loadingView = new LoadingView(getActivity());
//        refreshLayout.setBottomView(loadingView);
//        refreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
//            @Override
//            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
//                super.onRefresh(refreshLayout);
//                page = 1;
////                list.removeAll(list);
//                //initTitle();
//                getData(refreshLayout);
//            }
//
//            @Override
//            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
//                super.onLoadMore(refreshLayout);
//                page += 1;
//                getData(refreshLayout);
//            }
//        });
//    }

    List<HomePageListBean.ResultBean.BannerBean> arrayBanner = new ArrayList<>();

    HomePageListBean homePageListBean;

    List<ExplorationRoomBean.ResultBean.ListBean.DataBean> dataList = new ArrayList<>();

    ExplorationRoomBean.ResultBean.ListBean.DataBean dataBean;

    List<ExplorationRoomBean.ResultBean.ListBean.DataBean> hotList = new ArrayList<>();

    private void getData(final TwinklingRefreshLayout refreshLayout) {
//        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.SUP_LIST);
        RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.INFOSPACE_NEW_INDEX);
        params.addBodyParameter("p", page + "");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
                ExplorationRoomBean bean = gson.fromJson(jsonObject.toString(), ExplorationRoomBean.class);
                List<ExplorationRoomBean.ResultBean.ListBean> totalList = bean.getResult().getList();
                hotList = totalList.get(0).getData();

                OneAdapter oneAdapter = new OneAdapter(getActivity(), R.layout.item_one, hotList);
                View hotHeadView = LayoutInflater.from(getContext()).inflate(R.layout.item_room_text, (ViewGroup) rvHot.getParent(), false);
                TextView hotTextView = hotHeadView.findViewById(R.id.tv_title);
                hotTextView.setText(totalList.get(0).getTitle());
                oneAdapter.setHeaderView(hotHeadView);
                GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
                rvHot.addItemDecoration(new GridSpacingItemDecoration(4, 10, false));
                rvHot.setLayoutManager(gridLayoutManager);
                rvHot.setAdapter(oneAdapter);

                for (int i = 1; i < totalList.size(); i++) {
                    List<ExplorationRoomBean.ResultBean.ListBean.DataBean> data = totalList.get(i).getData();
                    for (int j = 0; j < data.size(); j++) {
                        dataBean = new ExplorationRoomBean.ResultBean.ListBean.DataBean();
                        dataBean.setTotalTitle(totalList.get(i).getTitle());
                        dataBean.setItemType(j);
                        dataBean.setTitle(data.get(j).getTitle());
                        dataBean.setAddress(data.get(j).getAddress());
                        dataBean.setCover_img(data.get(j).getCover_img());
                        dataBean.setPhone(data.get(j).getPhone());
                        dataBean.setId(data.get(j).getId());
                        dataList.add(dataBean);
                    }
                }
                TwoAdapter twoAdapter = new TwoAdapter(getActivity(), R.layout.item_exp_room_v, dataList);
                View headView = LayoutInflater.from(getContext()).inflate(R.layout.item_room_text, (ViewGroup) rvRoom.getParent(), false);
//                TextView textView = hotHeadView.findViewById(R.id.tv_title);
//                textView.setText(totalList.get(1).getTitle());
                twoAdapter.setHeaderView(headView);
                GridLayoutManager gridLayoutManager1 = new GridLayoutManager(getActivity(), 1);
                rvRoom.setLayoutManager(gridLayoutManager1);
                rvRoom.setAdapter(twoAdapter);
                oneAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        Intent intent = new Intent(getContext(), SupDetails.class);
                        intent.putExtra("supid", hotList.get(position).getId());
                        startActivity(intent);
                    }
                });
                twoAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        Intent intent = new Intent(getContext(), SupDetails.class);
                        intent.putExtra("supid", dataList.get(position).getId());
                        startActivity(intent);
                    }
                });
//                try {
//                    jsonArray = jsonObject.getJSONObject("result").getJSONArray("result");

//                    for (int i = 0; i < jsonArray.length(); i++) {
//                        JSONObject data = (JSONObject) jsonArray.get(i);
//                        ExplorationRoomBean.ResultBean.ListBean hotBean = gson.fromJson(((JSONObject) jsonArray.get(i)).toString(),ExplorationRoomBean.ResultBean.ListBean.class);
//                        hotBean.setTitle(data.getString("title"));
//
//                        ExplorationRoomBean.ResultBean.ListBean.DataBean infoBean = gson.fromJson(jsonArray.get(i).toString(), ExplorationRoomBean.ResultBean.ListBean.DataBean.class);
////                        ExplorationRoomBean.ResultBean.ListBean infoBean = gson.fromJson(jsonObject.toString(), ExplorationRoomBean.ResultBean.ListBean.class);
//                        infoBean.setItemType(2);
//                        infoBean.setCover_img(data.getString("cover_img"));
//                        infoBean.setId(data.getString("id"));
//                        infoBean.setAddress(data.getString("address"));
//                        infoBean.setTitle(data.getString("title"));
//                        infoBean.setPhone(data.getString("phone"));
//                        list.add(infoBean);
//                    }
////                    if (list.size() > 0) {
////                        nodata.setVisibility(View.GONE);
////                    } else {
////                        nodata.setVisibility(View.VISIBLE);
////                    }
//                    initList(list);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }


            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onError(String errorStr) {

            }
        });
    }

    private void initList(final List<ExplorationRoomBean.ResultBean.ListBean.DataBean> list) {
        if (page == 0) {
            mExplorationRoomAdapter = new ExplorationRoomAdapter(list, getActivity());
            rvRoom.setNestedScrollingEnabled(false);
            GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 1);
            rvRoom.setLayoutManager(gridLayoutManager);
            rvRoom.setAdapter(mExplorationRoomAdapter);

            mExplorationRoomAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    Log.e("id", list.get(position).getId());
                    Intent intent = new Intent(getContext(), SupDetails.class);
                    intent.putExtra("supid", list.get(position).getId());
                    startActivity(intent);
                }
            });
        } else {
            mExplorationRoomAdapter.notifyDataSetChanged();
        }
    }

    private void getNewsData() {
        OkHttpUtils.get()
                .url(GenesisApiConfig.HOST + GenesisApiConfig.HOME_PAGE)
                .addParams("p", page + "")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        Gson gson = new Gson();
                        homePageListBean = gson.fromJson(response, HomePageListBean.class);
                        getData(null);
                    }
                });

    }

    private void netBanner() {
        final RequestParams params = new RequestParams(GenesisApiConfig.HOST + GenesisApiConfig.BANNER_ADD);
        params.addBodyParameter("code", "app_tiyan_banner");
        NetWorkUtils.doCacheGet(params, new NetWorkUtils.HttpResultListener() {
            @Override
            public void onSuccess(JSONObject jsonObject) {
                Gson gson = new Gson();
                SpecialtyBannerBean bean = gson.fromJson(jsonObject.toString(), SpecialtyBannerBean.class);
                bannerList = bean.getResult().getList();
                initBanner();
            }

            @Override
            public void OnCached(JSONObject jsonObject) {
            }

            @Override
            public void onFinished() {
            }

            @Override
            public void onError(String errorStr) {
            }
        });
    }

    private void initBanner() {
        if (bannerList.size() <= 0 || bannerList == null) {
            banner.setVisibility(View.GONE);
        } else {
            banner.setVisibility(View.VISIBLE);
            List<String> bannerImages = new ArrayList<>();
            for (int i = 0; i < bannerList.size(); i++) {
                bannerImages.add(bannerList.get(i).getAdvert_img());
            }
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    ImageOptions imageOptions = new ImageOptions.Builder().setImageScaleType(ImageView.ScaleType.FIT_XY).build();
                    x.image().bind(imageView, GenesisApiConfig.PIC_HOST + (String) path, imageOptions);
                }
            });
            banner.setOnBannerListener(new OnBannerListener() {
                @Override
                public void OnBannerClick(int position) {
                    if (bannerList.get(position).getTarget_link().equals("")) {
                        Toast.makeText(getActivity(), "网络链接走丢了!", Toast.LENGTH_SHORT).show();
                    } else {
                        Intent intent = new Intent(getActivity(), WebActivity.class);
                        intent.putExtra("url", bannerList.get(position).getTarget_link());
                        startActivity(intent);
                    }
                }
            });
            banner.setIndicatorGravity(BannerConfig.CENTER);
            banner.isAutoPlay(true);
            banner.setDelayTime(5000);
            banner.setImages(bannerImages);
            banner.start();
        }
//        getData(null);
    }

}
